﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MoneyWentWhere.OutputHelpers;
using FileHelpers;
using MoneyWentWhere.Utils;

namespace MoneyWentWhere.SimpleTextFile.ExchangeRates
{
    [DelimitedRecord(",")]
    [IgnoreEmptyLines]
    public class ExchangeRate
    {
        public DateTime Date;
        public string FromCurrency;
        public string ToCurrency;

        [DisplayConverter(typeof(RateDisplayConverter))]
        public decimal Rate;

        public string Source; // optional

        public ExchangeRate(DateTime date, string fromCurrency, string toCurrency, decimal rate, string source)
        {
            if (String.IsNullOrEmpty(fromCurrency)) { throw new ArgumentException("fromCurrency"); }
            if (String.IsNullOrEmpty(toCurrency)) { throw new ArgumentException("toCurrency"); }
            if (rate <= 0) { throw new ArgumentException("rate=" + rate); }

            Date = date;
            FromCurrency = fromCurrency;
            ToCurrency = toCurrency;
            Rate = rate;
            Source = source;
        }

        public override string ToString()
        {
            return String.Format("{0}: 1 {1} = {3} {2} // {4}",
                DateConverter.FieldToString(Date),
                FromCurrency,
                ToCurrency,
                RateDisplayConverter.FieldToString(Rate),
                Source);
        }
    }

    class RateDisplayConverter : DisplayConverter
    {
        public override string FieldToString(object value)
        {
            decimal d = (decimal)value;
            return FieldToString(d);
        }

        public static string FieldToString(decimal d)
        {
            bool reciprocal = false;

            if (d < 1)
            {
                reciprocal = true;
                d = 1 / d;
            }

            // Need to show 3+ significant figures
            String format = (d >= 100) ? "#,##0" : "#0.00";

            return (reciprocal ? "1/" : "") + d.ToString(format);
        }
    }
}
